import React, { Component } from 'react';
import { base, ajax, formDownload, toast } from "nc-lightapp-front";
import getRandom from '../../../../../uap/public/getRandom';
const {NCModal, NCButton, NCTree} = base;
const {NCTreeNode} = NCTree;
const {Header: ModalHeader, Body: ModalBody, Footer: ModalFooter} = NCModal;

const x = 3;
const y = 2;
const z = 1;
const gData = [];

const generateData = (_level, _preKey, _tns) => {
  const preKey = _preKey || '0';
  const tns = _tns || gData;

  const children = [];
  for (let i = 0; i < x; i++) {
    const key = `${preKey}-${i}`;
    tns.push({
      title: key,
      key
    });
    if (i < y) {
      children.push(key);
    }
  }
  if (_level < 0) {
    return tns;
  }
  const level = _level - 1;
  children.forEach((key, index) => {
    tns[index].children = [];
    return generateData(level, key, tns[index].children);
  });
};
generateData(z);

const TreeNode = NCTree.NCTreeNode;


function getNewTreeData(treeData, curKey, child, level) {
    const loop = (data) => {
        if (level < 1 || curKey.length - 3 > level * 2) return;
        data.forEach((item) => {
            if (curKey.indexOf(item.id) === 0) {
                item.children = child;
            }
        });
    };
    loop(treeData);
}

class BatchFileDownModel extends Component {
    constructor(props) {
        super(props);
        this.state = {
            pk_psndocs:[],
            batchFileDownModeltreeData:[],
            showModal: false,
            retObj:[]
          };
        this.onClose = this.onClose.bind(this);
        this.onLoadData = this.onLoadData.bind(this);
    }

    onOk(refObj){
        this.props.updateState({
            batchFileDownModelVisiable: false
        });

        let data = {
            checkvalues : refObj
        }

        //下载
        formDownload({
			params:data,
            url:'/nccloud/hrhi/pub/batchFileDown.do',
            enctype:2
        });
        toast({ content: '操作成功', color: 'success' });
    }

    onClose() {
        this.props.updateState({
            batchFileDownModelVisiable: false
        });
    }

    onCheck = (checkedKeys,newst) => {
		//用户可以自定义当前选中和半选中的节点。
        this.props.updateState({
            retObj : checkedKeys
        })
	}

    componentDidMount() {
        setTimeout(() => {
          this.setState({
            batchFileDownModeltreeData: [
                {
                    refname: '附件分类',
                    id: 'root',
                    isleaf: false,
                    checkbox: true
                }
            ],
          });
        }, 100);
    }

    onLoadData(treeNode) {

        return new Promise((resovle, reject) => {
            const treeData = [...this.state.batchFileDownModeltreeData];
            if(treeNode.props.eventKey == 'root'){
                //只加根节点子集

                ajax({
                    url : '/nccloud/hrhi/pub/getNewTreeData.do',
                    data : this.props.pk_psndocs,
                    success: (res) => {
                        getNewTreeData(treeData, treeNode.props.eventKey, res.data, 2);

                        this.setState({
                            batchFileDownModeltreeData : treeData
                        });
                        resovle(res);
                        
                    },
                    error:(res) =>{
                        reject(res);
                    }
                });

            }else{
                this.setState({
                    batchFileDownModeltreeData : treeData
                });
                resovle();
            }

            
        })
    }

    render () {
        const { batchFileDownModelVisiable, retObj} = this.props;

        //树只有3级，1级复选框是根节点不可使用，2级复选框是分类可以使用，3级复选框是附件明细不可以使用
        const loop = data => data.map((item) => {
            if (item.children) {
              return <NCTreeNode disableCheckbox={item.checkbox} liAttr={{"fieldid":"originalData_node"}} title={item.refname} openIcon={<span className="iconfont icon-xinzengwenjianjia"/>}
                closeIcon={<span className="iconfont icon-xinzengwenjianjia"/>}
                key={item.id}>{loop(item.children)}</NCTreeNode>;
            }
            return <NCTreeNode disableCheckbox={item.checkbox} liAttr={{"fieldid":"originalData_node"}} title={item.refname} openIcon={<span className="iconfont icon-xinzengwenjianjia"/>}
              closeIcon={<span className="iconfont icon-xinzengwenjianjia"/>}
              key={item.id} isLeaf={item.isleaf}/>;
        });

        const treeNodes = loop(this.state.batchFileDownModeltreeData);

        return (
            <div>
                <NCModal
                    show = {batchFileDownModelVisiable}
                    onHide={this.onClose}
                    //  bodyStyle={{ height: '700px' }}
                    >
                    <ModalHeader closeButton={true} draggable={true}>
                        <span>附件批量下载</span>
                    </ModalHeader>
                    <ModalBody style={{ textAlign: 'center' }}>
                    <div style={{ width: 360, display: 'inline-block' }}>
                        <NCTree
                        className="myCls"
                        showLine
                        checkable
                        // checkStrictly
                        showIcon
                        // defaultExpandedKeys={['root']}
                        // cancelUnSelect={true}
                        onCheck={this.onCheck.bind(this)}
                        loadData={this.onLoadData}
                        >
                            {treeNodes}
                        </NCTree>
                    </div>

                    </ModalBody>
                    <ModalFooter>
                        <NCButton colors="primary" onClick={this.onOk.bind(this, retObj)}>确认</NCButton>
                        <NCButton onClick={this.onClose}>取消</NCButton>
                    </ModalFooter>
                </NCModal>
            </div>
        )
    }
}

export default BatchFileDownModel;